package com.cykj.faceledtv.ui.base;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.cykj.faceledtv.MyApp;
import com.cykj.faceledtv.R;
import com.cykj.faceledtv.di.component.ActivityComponent;
import com.cykj.faceledtv.di.component.DaggerActivityComponent;
import com.cykj.faceledtv.di.module.ActivityModule;
import com.cykj.faceledtv.utils.ScreenSwitch;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.Unbinder;

/**
 * activity基类
 *
 * @author jzh
 * @date 2018/12/13 09:03
 */
public abstract class BaseActivity extends AppCompatActivity implements MvpView, BaseFragment.Callback {

    private Unbinder mUnBinder;
    private FragmentManager fragmentManager;
    private BaseFragment showFragment;
    private ActivityComponent mActivityComponent;
    /**
     * 判断是否需要检测权限，防止不停的弹框
     */
    public boolean isNeedCheck = true;
    private static final int PERMISSION_REQUEST_CODE = 0;

    private boolean mStateEnable = true;
    private int sdkInt = 23;

    /**
     * 得到布局id
     *
     * @return 布局id
     */
    protected abstract int getLayoutId();

    /**
     * 初始化控件
     */
    protected abstract void initWidget();


    /**
     * 设置屏幕全屏等初始化操作
     */
    protected void beForSet() {

    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentManager = getSupportFragmentManager();
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        mActivityComponent = DaggerActivityComponent.builder()
                .activityModule(new ActivityModule(this))
                .applicationComponent(((MyApp) getApplication()).getComponent())
                .build();
        beForSet();
        if (getLayoutId() != 0) {
            setContentView(getLayoutId());
        }
        initWidget();
        MyApp.getInstance().addActivity(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mStateEnable = true;
    }

    public ActivityComponent getActivityComponent() {
        return mActivityComponent;
    }


    /**
     * 检查权限
     *
     * @param permissions 权限组
     * @since 2.5.0
     */
    public void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= sdkInt
                    && getApplicationInfo().targetSdkVersion >= sdkInt) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    Class[] mClass = new Class[]{String[].class, int.class};
                    Method method = getClass().getMethod("requestPermissions", mClass);
                    method.invoke(this, array, PERMISSION_REQUEST_CODE);
                } else {
                    checkPermissionsSuccess();
                }
            } else {
                checkPermissionsSuccess();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 所有授权都成功了
     */
    public void checkPermissionsSuccess() {
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions permissions
     * @return 集合
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= sdkInt
                && getApplicationInfo().targetSdkVersion >= sdkInt) {
            try {
                for (String perm : permissions) {
                    Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
                    Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
                            String.class);
                    if ((Integer) checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
                            || (Boolean) shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否所有的权限都已经授权
     *
     * @param grantResults 权限组
     * @return 是否已授权
     * @since 2.5.0
     */
    public boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] paramArrayOfInt) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            } else {
                checkPermissionsSuccess();
            }
        }
    }


    @Override
    protected void onResume() {
        mStateEnable = true;
        super.onResume();
    }

    /**
     * 显示缺少权限提示信息
     *
     * @since 2.5.0
     */
    public void showMissingPermissionDialog() {
        new AlertDialog.Builder(this)
                .setMessage(R.string.notifyMsg).setTitle(R.string.tips)
                .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startAppSettings();
                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MyApp.getInstance().exit();
            }
        }).create().show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
        isNeedCheck = true;
    }

    /**
     * 是否拥有所有需要的权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    public boolean hasAllPermissions(String... permissions) {
        for (String permission : permissions) {
            if (!hasPermission(permission)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 单个权限检查
     *
     * @param permission permission
     * @return true or false
     */
    @TargetApi(Build.VERSION_CODES.M)
    public boolean hasPermission(String permission) {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
                checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }


    @Override
    public void onFragmentAttached() {

    }

    @Override
    public void onFragmentDetached(String tag) {

    }

    @Override
    public void hideKeyboard() {
        if (isFinishing()) {
            return;
        }
        View view = this.getCurrentFocus();
        if (null == view) {
            return;
        }
        try {
            InputMethodManager inputManager = (InputMethodManager) view.getContext().getApplicationContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            // 即使当前焦点不在editText，也是可以隐藏的。
            inputManager.hideSoftInputFromWindow(view.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setUnBinder(Unbinder unBinder) {
        mUnBinder = unBinder;
    }


    @Override
    protected void onDestroy() {
        if (mUnBinder != null) {
            mUnBinder.unbind();
        }
        MyApp.getInstance().removeActivity(this);
        super.onDestroy();
    }

    public void goActivityForResult(Class<?> descClass, int requestCode) {
        ScreenSwitch.switchActivity(this, descClass, null, requestCode);
    }

    public void goActivityForResult(Class<?> descClass, Bundle bundle, int requestCode) {
        ScreenSwitch.switchActivity(this, descClass, bundle, requestCode);
    }

    public void goActivity(Class<?> descClass, Bundle bundle) {
        goActivityForResult(descClass, bundle, 0);
    }

    public void goActivity(Class<?> descClass) {
        goActivity(descClass, null);
    }

    public void showFragment(int resId, BaseFragment fragment) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (showFragment != null) {
            if (showFragment.getClass().getName().equals(fragment.getClass().getName())) {
                return;
            }
            fragmentTransaction.hide(showFragment);
        }
        Fragment mFragment = fragmentManager.findFragmentByTag(fragment.getClass().getName());
        if (mFragment != null) {
            fragmentTransaction.show(mFragment);
            showFragment = (BaseFragment) mFragment;
        } else {
            fragmentTransaction.add(resId, fragment, fragment.getClass().getName());
            showFragment = fragment;
        }
        if (mStateEnable) {
            fragmentTransaction.commit();
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mStateEnable = false;
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStop() {
        mStateEnable = false;
        super.onStop();
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent me) {
        try {
            if (me.getAction() == MotionEvent.ACTION_DOWN) {  //把操作放在用户点击的时候
                View v = getCurrentFocus();      //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
                if (isShouldHideKeyboard(v, me)) { //判断用户点击的是否是输入框以外的区域
                    hideKeyboard(v.getWindowToken());   //收起键盘
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.dispatchTouchEvent(me);
    }


    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {  //判断得到的焦点控件是否包含EditText
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],    //得到输入框在屏幕中上下左右的位置
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
